<template>
  <el-dialog
    v-el-drag-dialog
    title="创建安检计划"
    :visible.sync="visible"
    width="700px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="left" label-width="130px">

      <el-form-item label="计划名称:" prop="planName" style="width: 100%;">
        <el-input v-model="temp.planName" placeholder="请输入计划名称" clearable />
      </el-form-item>

      <el-form-item label="安检范围:" prop="orgIds">
        <el-tree-select
          ref="treeSelect"
          v-model="temp.orgIds"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            multiple: true,
            placeholder: '请选择',
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>

      <el-form-item label="客户类型:" prop="mineStatus" multiple label-width="100px">
        <el-select v-model="temp.mineStatus" multiple placeholder="请选择">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in mineStatusMap"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
        <!-- <el-select v-model="temp.mineStatus" placeholder="请选择客户类型" multiple :popper-append-to-body="false" @change="selectChange">
          <el-option :value="mineStatusValue" style="height: auto;">
            <el-tree ref="tree" :data="csmData" show-checkbox node-key="id" highlight-current :props="defaultProps" default-expand-all @check-change="handleCheckChange" />
          </el-option>
        </el-select> -->
      </el-form-item>

      <el-form-item class="merge-item" label="安检到期时间在:" style="width: 100%;" prop="date">
        <el-date-picker
          v-model="temp.date"
          type="daterange"
          unlink-panels
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button type="primary" :loading="loading" @click="success">
        生成
      </el-button>
    </div>
    <newly-increased ref="newlyIncreased" :csm-type-map="csmTypeMap" :tree-data="treeData" :csm-status-map="csmStatusMap" @upDataTable="upDataTable" />
  </el-dialog>
</template>

<script>
  import { gasCheckPlanClientAssignSave } from '@/api'
  import NewlyIncreased from './NewlyIncreased'
  import moment from 'dayjs'
  export default {
    name: 'add',
    components: {
      NewlyIncreased
    },
    props: {
      csmTypeMap: {
        type: Array,
        required: true
      },
      treeData: {
        type: Array,
        required: true
      },
      csmStatusMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        loading: false,
        visible: false,
        csmVal: 'csmRgPhone',
        temp: {
          planName: '',
          mineStatus: '',
          orgIds: [],
          date: []
        },
        csmType: [],
        params: {},
        rules: {
          planName: [{ required: true, message: '请输入计划名称', trigger: 'change' }],
          orgIds: [{ required: true, message: '请选择安检范围', trigger: 'change' }],
          mineStatus: [{ required: true, message: '请选择客户类型', trigger: 'change' }],
          date: [{ required: true, message: '请选择安检到期开始时间', trigger: 'change' }]
        },
        mineStatusMap: [
          {
            id: '1',
            label: '居民',
            value: 2
          },
          {
            id: '2',
            label: '商业',
            value: 4
          },
          {
            id: '4',
            label: '工业',
            value: 16
          }
        ],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        mineStatusValue: [],
        orgSNNoArray: [],
        scopeNames: [],
        orgIds: []
      }
    },
    computed: {
    },
    watch: {
      'temp.mineStatus': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.temp.mineStatus = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.temp.mineStatus.splice(val.indexOf(0), 1)
        }
        if (this.temp.mineStatus.length === this.mineStatusMap.length) {
          this.temp.mineStatus = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      }
    },
    async created() {},
    methods: {
      open(temp) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.$nextTick(() => {
            this.$refs.dataForm.clearValidate()
          })
        })
      },
      success() {
        // eslint-disable-next-line no-unused-vars
        this.loading = true
        var csmType = []
        if (this.temp.mineStatus === []) {
          this.$message({
            type: 'error',
            message: '请选择客户类型'
          })
          this.loading = false
          return
        }
        if (this.temp.mineStatus[0] === 0) {
          csmType = ['0', '1', '2', '4']
        } else {
          csmType = [...this.temp.mineStatus]
        }
        this.csmType = csmType
        this.checkChange()
        this.$refs.dataForm.validate(valid => {
          if (!valid) {
            this.loading = false
            return
          }
          this.params.csmType = csmType
          this.params.orgSNNos = this.orgSNNoArray
          this.params.scopeNames = this.scopeNames
          this.params.orgIds = this.orgIds
          this.params.planName = this.temp.planName
          this.params.beginDt = moment(this.temp.date[0]).format()
          this.params.endDt = moment(this.temp.date[1]).format()
          this.add()
        })
      },
      async add() {
        const res = await gasCheckPlanClientAssignSave(this.params)
        let str = 0
        if (this.csmType.toString() === ['0', '1', '2', '4'].toString()) {
          str = 22
        } else {
          this.mineStatusMap.map(item => {
            if (this.csmType.indexOf(item.id) !== -1) {
              str += Number(item.value)
            }
          })
        }
        const obj = {
          planCode: res.data,
          planName: this.temp.planName,
          csmTypes: str,
          scopeNames: this.params.scopeNames
        }
        this.visible = false
        setTimeout(() => {
          this.loading = false
        }, 1000)
        this.$refs.newlyIncreased.open(obj)
      },
      reset() {
        this.visible = false
        this.csmVal = 'csmRgPhone'
        this.temp = {
          planName: '',
          mineStatus: '',
          orgIds: [],
          date: []
        }
        this.csmData = [{
          id: 0,
          label: '全部',
          children: [
            {
              id: 1,
              label: '居民'
            },
            {
              id: 2,
              label: '商业'
            },
            {
              id: 4,
              label: '工业'
            }
          ]
        }]
        this.params = {}
        this.defaultProps = {
          children: 'children',
          label: 'label'
        }
        this.mineStatusValue = []
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      },
      upDataTable() {
        this.$emit('updateTableData')
      },
      checkChange() {
        const node = this.$refs.treeSelect.$refs.tree.getCheckedNodes()
        console.log(node)
        const orgSNNoArray = []
        const orgIds = []
        let scopeNames = ''
        node.map(item => {
          orgSNNoArray.push(item.orgSNNo)
          orgIds.push(item.orgId)
          scopeNames = scopeNames + item.orgName + ','
        })
        this.orgSNNoArray = orgSNNoArray
        this.scopeNames = scopeNames
        this.orgIds = orgIds
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  /deep/.el-select-dropdown__item {
    padding: 0 !important;
    padding-right: 0 !important;
  }
}
</style>
